
package com.the9tcat.deliverycoming;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import com.the9tcat.deliverycoming.data.Configure;
import com.the9tcat.deliverycoming.util.Logger;

public class AlarmReceiver extends BroadcastReceiver {

    public static final String START_ALARM = "START_ALARM";

    public static final String CANCLE_ALARM = "CANCLE_ALARM";

    private static final String LOG_TAG = "AlarmReceiver";

    private AlarmManager mAlarm;

    @Override
    public void onReceive(Context context, Intent intent) {
        
        Logger.d(LOG_TAG, "onReceive");
        mAlarm = (AlarmManager) context
                .getSystemService(Context.ALARM_SERVICE);
        if (intent != null && !TextUtils.isEmpty(intent.getAction())) {

            if (intent.getAction().equals(START_ALARM)) {

                startAlarm(context);

            } else if (intent.getAction().equals(
                    CANCLE_ALARM)) {

                cancelAlarm(context);

            }

        }
    }

    private void startAlarm(Context context) {
        Logger.d(LOG_TAG, "Start alarm");
        long now = System.currentTimeMillis();
        Intent i = new Intent(context, MessengerService.class);
        PendingIntent pintent = PendingIntent.getService(
                context, 0, i, 0);
        mAlarm.setRepeating(AlarmManager.RTC, now, Configure.getInstance(context).getUpdateFreq(),
                pintent);
    }

    /**
     * Cancel alarm.
     * 
     * @param action the action
     */
    private void cancelAlarm(Context context) {
        Logger.d(LOG_TAG, "Cancel alarm");

        Intent i = new Intent(context, MessengerService.class);
        PendingIntent pintent = PendingIntent.getService(
                context, 0, i, 0);
        mAlarm.cancel(pintent);
    }

}
